package cn.ybz21.hibot.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.ybz21.hibot.bean.Task;

public class TaskDAO extends BaseDAO{
	private String NAME_TABLE = "tasks";
	/**
	 * 根据id获取任务
	 * 
	 * @param id
	 * @return
	 */
	public Task queryTaskById(String id) {
		Task tempTask = null;
		String sql = "select * from  " + NAME_TABLE + "  where id=?";
		Connection conn = db.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			int index = 1;
			pstmt.setObject(index++, id);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				tempTask = new Task(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();

		}
		db.close(conn, pstmt, rs);
		return tempTask;
	}

	/**
	 * 获取分页任务
	 * 
	 * @param startPage
	 * @param pageSize
	 * @return
	 */
	public List<Task> queryTasks(int startPage, int pageSize) {
		int pageIndex = (startPage - 1) * pageSize;
		List<Task> tasks = new ArrayList<Task>();
		String sql = "select * from " + NAME_TABLE + " limit ?,?";
		Connection conn = db.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			int index = 1;
			pstmt.setInt(index++, pageIndex);
			pstmt.setInt(index++, pageSize);
			rs = pstmt.executeQuery();
			while (rs.next()) {

				Task tempTask = new Task(rs);
				tasks.add(tempTask);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		db.close(conn, pstmt, rs);
		return tasks;
	}
}
